import store from '../store'
import Vue from 'vue'
// 创建可销毁，可外部操作的 promise
const _promise = function _promise (func) {
  let resolve, reject

  function f (e) {
    return (...arg) => {
      if (p.isOver) return
      p.isOver = true
      e(...arg)
    }
  }

  let p = new Promise((_resolve, _reject) => {
    resolve = f(_resolve)
    reject = f(_reject)
    func && func(resolve, reject)
  })
  p.resolve = resolve
  p.reject = reject
  p.isOver = false
  p.destroy = () => {
    console.log('销毁')
    if (p.isOver) return false
    p.destroy_callback && p.destroy_callback()
    return p.isOver = true
  }
  let _finally = p.finally.bind(p)
  p.finally = (fun) => {
    if (p.isOver) {
      fun && fun()
      return p
    } else {
      p.destroy_callback = fun
      return _finally(fun)
    }
  }
  return p
}

// 定时 promise
const sleep = function (duration = 0) {
  return new Promise(function (resolve, reject) {
    setTimeout(() => resolve(duration), duration)
  })
}

// 判断空
const isEmpty = value => value === undefined || value === null || value === ''

// 用户保存当前页面是后退还是前进
let navigationDirection = null

const addPop = (payload) => {
  store.state.popQueue.add(payload)
}

const closePop = (popQueue) => {
  popQueue()
  return store.state.popQueue.delete(popQueue)
}

/*-----------全局弹窗 begin--------------*/
const m_alert = function (content, title = '温馨提示') {
  Vue.$vux.alert.show({
    title,
    content
  })
}

const m_toast = function (text, position = 'center') {
  Vue.$vux.toast.text(text, 'top', position)
}

const m_loading = function (text) {
  Vue.$vux.loading.show({text})
}
m_loading.hide = Vue.$vux.loading.hide
/*-----------全局弹窗 end--------------*/


Object.assign(window, {
  _promise, sleep, isEmpty, navigationDirection, addPop, closePop, m_alert, m_toast, m_loading
})
Object.assign(Vue.prototype, {isEmpty})